# To change this template, choose Tools | Templates
# and open the template in the editor.
import pygame
from pygame.locals import *

class Widget:
    def __init__(self, **args):
        
        self.widget_type = 'widget'

        args.setdefault("image",None)
        args.setdefault("align",-1)
        args.setdefault("valign",-1)
        args.setdefault("padding", (0,0,0,0))
        args.setdefault("rect", Rect(0,0,0,0))
        args.setdefault("color", (255,255,255,255))

        args.setdefault("font",pygame.font.SysFont("Tahoma", 13))

        self.rect = args["rect"]
        self.image = args["image"]
        self.align = args["align"]
        self.valign = args["valign"]
        self.font = args["font"]
        self.color = args["color"]
        self.padding = args["padding"]

        if "width" in args:
            self.rect[2] = args["width"]
        if "height" in args:
            self.rect[3] = args["height"]

        #adjust the rect according to the padding
        self.rect[0] += self.padding[3]
        self.rect[1] += self.padding[0]

        self.rect[2] -= self.padding[1] + self.padding[3]
        self.rect[3] -= self.padding[0] + self.padding[2]
            
        self.min_size = [0,0]
        self.max_size = None
        self.parent = None

        self.enable = 1

        self.make_dirty()


    def draw(self, canvas, area=None):
        if area is None:
            area = self.rect

        if self.dirty:
            self.draw_img()
            self.canvas = pygame.Surface(
                (area[2] + self.padding[1] + self.padding[3],
                area[3] + self.padding[0] + self.padding[2])).convert()
            self.canvas.fill((0,255,255))
            self.canvas.set_colorkey((0,255,255))
            if self.image is not None:
                self.canvas.blit(self.image, (self.padding[3], self.padding[0]))
            canvas.blit(self.canvas, (area[0], area[1]))
            self.dirty = 0
        else:
            canvas.blit(self.canvas, (area[0], area[1]))

    def draw_img(self):
        pass

    def pos(self):
        return (self.rect[0], self.rect[1])


    def make_dirty(self):
        self.dirty = 1
        if self.parent is not None:
            self.parent.make_dirty()

    def constrain(self, s):

        if s[0] < self.min_size[0]:
            s[0] = self.min_size[0]
        if s[1] < self.min_size[1]:
            s[1] = self.min_size[1]

        if s[0] > self.max_size[0]:
            s[0] = self.max_size[0]
        if s[1] > self.max_size[1]:
            s[1] = self.max_size[1]

        return s

    def pack(self):
        return self.constrain(self.rect.size)

    def set_pos(self, pos):
        self.rect[0], self.rect[1] = pos[0], pos[1]

    def receive(self, dat, evt):
        return 0